﻿using System.Linq;
using System.Threading.Tasks;
using CRM.Extensions;
using CRM.Models;
using CRM.Models.Email;
using CRM.ViewModels.Email;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace CRM.Controllers.Email
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmailSendHistoryController : BaseController
    {
        private readonly MyDbContext _dbContext;
        private readonly UserManager<User> _userManager;
        public EmailSendHistoryController(MyDbContext dbContext, UserManager<User> userManager)
        {
            _dbContext = dbContext;
            _userManager = userManager;
        }

        [HttpPost(nameof(Index))]
        public async Task<ResultStruct> Index(EmailSendHistoryListQuery query)
        {
            var user = await _userManager.GetUserAsync(User);
            var result =
                await _dbContext.EmailSendHistory
                    .Where(m => m.OemId == user.OemId && m.CompanyId == user.CompanyId && m.GroupId == user.GroupId && m.UserId == user.Id)
                    .WhenWhere(!string.IsNullOrEmpty(query.MarketingTaskName), m => m.MarketingTaskName.StartsWith(query.MarketingTaskName) || m.MarketingTaskName.EndsWith(query.MarketingTaskName))
                    .WhenWhere(query.State.IsNotNull(), m => m.State == query.State)
                    .WhenWhere(query.Flag > 0, m => (m.Details & query.Flag) == query.Flag)
                    .WhenWhere(query.NegativeFlag > 0, m => (~m.Details & query.NegativeFlag) == query.NegativeFlag)
                    .WhenWhere(query.SendingType != 0 && query.SendingType != null, m => m.SendingType == query.SendingType)
                    // .WhenWhere(query.EmailPlatform != null, m => m.EmailPlatform == query.EmailPlatform)
                    .WhenWhere(query.CreatedAt != null && query.CreatedAt.Length == 2, m => m.CreatedAt >= query.CreatedAt[0] && m.CreatedAt <= query.CreatedAt[1].AddDays(1))
                    .OrderByDescending(m => m.Id)
                    .ToPaginateAsync(query.Page, query.Limit);
            return Success(result);
        }

        [HttpPost(nameof(SendingFree))]
        public async Task<ResultStruct> SendingFree(EmailSendHistoryListQuery query)
        {
            return await Index(query);
        }    
        
        [HttpPost("[action]")]
        public async Task<ResultStruct> SendingFreeCreate(EmailSendHistoryVM vm)
        {
            var user = await _userManager.GetUserAsync(User);
            if (!ModelState.IsValid) return Error(message: ModelState.ToString());
            var model = vm.NewModel(_dbContext,user);
            await _dbContext.EmailSendHistory.AddAsync(model);
            var emailMarket = await _dbContext.EmailMarketing
                .Where(m => m.OemId == user.OemId && m.CompanyId == user.CompanyId && m.GroupId == user.GroupId &&
                            m.UserId == user.Id)
                .Where(m => m.Id == model.Source).FirstOrDefaultAsync();
            
            switch (vm.Action)
            {
                case "First":
                {
                    emailMarket.SetState(EmailMarketing.StateEnum.Submitted);
                    break;
                }
                case "Complete":
                {
                    emailMarket.SetState(EmailMarketing.StateEnum.Completed);
                    var num = await _dbContext.EmailSendHistory
                        .Where(m => m.OemId == user.OemId && m.CompanyId == user.CompanyId && m.GroupId == user.GroupId &&
                                    m.UserId == user.Id).Where(m => m.Source == model.Source).CountAsync();
                    _dbContext.Entry(emailMarket).Increment(m => m.SendingNum, 1);
                    break;
                }
                default: /* 可选的 */
                    break;
            }
            await _dbContext.SaveChangesAsync();
            return Success();
        }

        [HttpPost(nameof(SendingByServer))]
        public async Task<ResultStruct> SendingByServer(EmailSendHistoryListQuery query)
        {
            return await Index(query);
        }
        
        [HttpPost(nameof(Create))]
        public async Task<ResultStruct> Create(EmailSendHistoryVM vm)
        {
            var user = await _userManager.GetUserAsync(User);
            if (!ModelState.IsValid) return Error(message: ModelState.ToString());
            var model = vm.NewModel(_dbContext,user);
            await _dbContext.EmailSendHistory.AddAsync(model);
            await _dbContext.SaveChangesAsync();
            return Success();
        }

        [HttpGet(nameof(Info))]
        public async Task<ResultStruct> Info([FromQuery] int id)
        {
            var user = await _userManager.GetUserAsync(User);
            var result = await _dbContext.EmailSendHistory
                .Where(m => m.OemId == user.OemId && m.CompanyId == user.CompanyId && m.GroupId == user.GroupId && m.UserId == user.Id)
                .Where(m => m.Id == id)
                .FirstAsync();
            return Success(result);
        }
        
        [HttpGet(nameof(EmailMarketingHistory))]
        public async Task<ResultStruct> EmailMarketingHistory([FromQuery] int id)
        {
            var user = await _userManager.GetUserAsync(User);
            var result = await _dbContext.EmailSendHistory
                .Where(m => m.OemId == user.OemId && m.CompanyId == user.CompanyId && m.GroupId == user.GroupId && m.UserId == user.Id)
                .Where(m=> m.Source == id)
                .ToArrayAsync();
            return Success(result);
        }
        
        #nullable enable
        [Route("[action]")]
        public async Task<ResultStruct> GetDetailsByMessageId([FromQuery] long messageId,string? eventType)
        {
            var result = await _dbContext.WebhookEventDetails.Where(m => m.MessageId == messageId)
                .WhenWhere(eventType.IsNotNull(), m => m.Event == eventType).ToArrayAsync();
            return Success(result);
        }
        
        #nullable restore
    }
}